package com.house.framework.controller;

import com.alibaba.fastjson.JSONObject;
import com.house.annotations.NoAuthentication;
import com.house.framework.service.ExportService;
import com.house.utils.PathKit;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/exportExcel")
public class ExportExcelController extends BaseController {

    @Autowired
    ExportService exportService;

    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public JSONObject exportExcel(@RequestBody JSONObject form) {
        return exportService.exportExcel(form);
    }

    @NoAuthentication
    @ApiOperation(value = "文件下载", notes = "targetName下载文件名")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void downloadWarFile(HttpServletRequest request, HttpServletResponse response, @RequestParam String targetName) throws IOException {
        String fileUrl = targetName + ".xls";
        String filePath = PathKit.getClassPath() + "/Excel/";
        File file = new File(filePath + "/" + fileUrl);
        String mimeType = request.getServletContext().getMimeType(fileUrl);
        response.setContentType(mimeType);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(fileUrl,"UTF-8"));
        response.setCharacterEncoding("UTF-8");
        byte[] buff = new byte[1024];
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); OutputStream os = response.getOutputStream()) {
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        }
    }
}
